<?php
class AppModel extends Model
{
	private $sql_function = array("CURDATE()","NOW()");
	public $sanitize;

	const ACTIVATE   = 1;
	const DEACTIVATE = 0;


    public function myGenerateList($conditions = null, $order = null, $limit = null, $keyPath = null, $valuePath = null, $separator = '')
    {
        if ($keyPath == null && $valuePath == null && $this->hasField($this->displayField)) {
          $fields = array($this->primaryKey, $this->displayField);
        } else {
          $fields = null;
        }
        $recursive = $this->recursive;
        $result = $this->findAll($conditions, $fields, $order, $limit);
        $this->recursive = $recursive;

        if(!$result) {
          return false;
        }

        if ($keyPath == null) {
          $keyPath = '{n}.' . $this->name . '.' . $this->primaryKey;
        }

        if ($valuePath == null) {
          $valuePath = '{n}.' . $this->name . '.' . $this->displayField;
        }

        // extract the keys as normal
        $keys = Set::extract($result, $keyPath);


        $finalVals = array();

        // explode the value path by our delimiter
        $tmpVals = explode('#', $valuePath);

        $i = 0;
        foreach($tmpVals as $tmpVal) {
          // extract the data for each path sibling
          $vals = Set::extract($result, $tmpVal);

          // and insert it at the appropriate position in our final value array
          // use the separator when we need to append the values
          foreach($vals as $key => $value) {
            if(!array_key_exists($key, $finalVals)) {
              $finalVals[$key] = $value;
            } else {
              $finalVals[$key] .= $separator.$value;
            }
          }
          $i++;
        }


        if (!empty($keys) && !empty($finalVals)) {
          $out = array();
          $return = array_combine($keys, $finalVals);
          return $return;
        }
        return null;
    }


    /**
     * @param integer $id
     * @param array $value
     *
     * @return $id if successfully and null if error
     */
    public function _save($value = array(), $id = 0)
    {
        $this->id = $id;
        if (is_array($value)) {
            $rs = $this->save($value, array('validate' => true));
            if ($rs) {
                 if ($this->id > 0) {
                     return $this->id;
                 } else {
                     return array('id' => $this->{$this->name}->getInsertID());
                 }
            } else {
                return $this->invalidFields();
            }
        } else {
            return null;
        }
    }

    /**
     * @desc execute custom insert statement
     *
     * @param $data
     * @return unknown_type
     */
    public function __insert($data = array())
    {
    	if (!is_array($date)) return null;

		// initialize with open parens
		$ftxt = $vtxt = "(";

		// Iterate over the values hash
		$first = true;

		foreach ($values as $key => $val) {
			if ($first) {
				$first = false;
			} else {
				$ftxt .= ", ";
				$vtxt .= ", ";
			}
			$ftxt .= "`" . mysql_escape_string($key) . "`";
			// SQL functions are not quoted or escaped...
			if (array_search($val, $this->sql_function)) {
				$vtxt .= $val;
			} else {
				$vtxt .= "'" . mysql_escape_string($val) . "'";
			}
		}
		$ftxt .= ")";
		$vtxt .= ")";

		$query = "INSERT INTO `" . mysql_escape_string($table) . "` " . $ftxt
		. " VALUES " . $vtxt;

		self::__query($query);
		$id = self::__query("SELECT LAST_INSERT_ID();", true);
		return $id[0][0];
    }

	/**
	 * Do an arbitrary database query.  $query is the SQL query to
	 * be executed.  It will return the result of the query as is, or
	 * the result set as an array if $fetcharray is true.
	 */

    /*
    public function __query($query, $fetcharray = FALSE)
    	{
    		$result = @mysql_query($query, $this->link)
    		or $this->error_msg(mysql_error(), " Error in mysql query ".
    		$query . ".");
    		if ($fetcharray) {
    			// Build $result as an array
    			$res = $result;
    			$result = array();
    			while ($line = mysql_fetch_array($res, MYSQL_BOTH)) {
    				$result[] = $line;
    			}
    		}

    		return $result;
    	}
    */


    public function alphaNumericDash($data) {
      // $data array is passed using the form field name as the key
      // have to extract the value to make the function generic
      $value = array_values($data);
      $value = $value[0];

      return preg_match('|^[0-9a-zA-Z-]*$|', $value);
    }

    public function __find($type, $options = array()) {
        if (!isset($options['joins'])) {
            $options['joins'] = array();
        }

        switch ($type) {
            case 'matches':
                if (!isset($options['model']) || !isset($options['scope'])) {
                    break;
                }
                $assoc = $this->hasAndBelongsToMany[$options['model']];
                $bind = "{$assoc['with']}.{$assoc['foreignKey']} = {$this->alias}.{$this->primaryKey}";

                $options['joins'][] = array(
                    'table' => $assoc['joinTable'],
                    'alias' => $assoc['with'],
                    'type' => 'inner',
                    'foreignKey' => false,
                    'conditions'=> array($bind)
                );

                $bind = $options['model'] . '.' . $this->{$options['model']}->primaryKey . ' = ';
                $bind .= "{$assoc['with']}.{$assoc['associationForeignKey']}";

                $options['joins'][] = array(
                    'table' => $this->{$options['model']}->table,
                    'alias' => $options['model'],
                    'type' => 'inner',
                    'foreignKey' => false,
                    'conditions'=> array($bind) + (array)$options['scope'],
                );
                unset($options['model'], $options['scope']);
                $type = 'all';
            break;
        }
        return parent::find($type, $options);
    }

//    public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
//    	$recursive = -1;
//    	$group = $fields = array('week', 'away_team_id', 'home_team_id');
//    	return $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group'));
//    }
}
?>